package io.framework.modules.security.service.impl;

import io.framework.common.constant.Constant;
import io.framework.common.exception.ErrorCode;
import io.framework.common.service.impl.BaseServiceImpl;
import io.framework.common.utils.ConvertUtils;
import io.framework.common.utils.MessageUtils;
import io.framework.modules.security.oauth2.TokenGenerator;
import io.framework.common.utils.Result;
import io.framework.modules.security.dao.SysUserTokenDao;
import io.framework.modules.security.entity.SysUserTokenEntity;
import io.framework.modules.security.service.SysUserTokenService;
import io.framework.modules.sys.dto.SysUserDTO;
import io.framework.modules.sys.entity.SysUserEntity;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class SysUserTokenServiceImpl extends BaseServiceImpl<SysUserTokenDao, SysUserTokenEntity> implements SysUserTokenService {
    /**
     * 12小时后过期
     */
    private final static int EXPIRE = 3600 * 12 * 15;

    @Override
    public Result createToken(Long userId,String flag) {
        //用户token
        String token;

        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

        //判断是否生成过token
        SysUserTokenEntity tokenEntity = baseDao.getByUserId(userId);
        if (tokenEntity == null) {
            //生成一个token
            token = TokenGenerator.generateValue();

            tokenEntity = new SysUserTokenEntity();
            tokenEntity.setUserId(userId);
            tokenEntity.setToken(token);
            tokenEntity.setUpdateDate(now);
            tokenEntity.setExpireDate(expireTime);

            //保存token
            this.insert(tokenEntity);
        } else {
            //判断token是否过期
            if (tokenEntity.getExpireDate().getTime() < System.currentTimeMillis()) {
                //token过期，重新生成token
                token = TokenGenerator.generateValue();
            } else {
                token = tokenEntity.getToken();
            }

            tokenEntity.setToken(token);
            tokenEntity.setUpdateDate(now);
            tokenEntity.setExpireDate(expireTime);

            //更新token
            this.updateById(tokenEntity);
        }

        Map<String, Object> map = new HashMap<>(2);
        map.put(Constant.TOKEN_HEADER, token);
        map.put("expire", EXPIRE);
        map.put("flag", flag);
        return new Result().ok(map);
    }

    @Override
    public void logout(Long userId) {
        //生成一个token
        String token = TokenGenerator.generateValue();

        //修改token
        baseDao.updateToken(userId, token);
    }

    @Override
    public SysUserTokenEntity getByToken(String token) {
        return baseDao.getByToken(token);
    }

    @Override
    public SysUserDTO getUserInfobytoken(String token) {
        System.out.println("------------token:" + token);
        SysUserTokenEntity tokenEntity = getByToken(token);
        //token失效
        if (tokenEntity == null || tokenEntity.getExpireDate().getTime() < System.currentTimeMillis()) {
            throw new IncorrectCredentialsException(MessageUtils.getMessage(ErrorCode.TOKEN_INVALID));
        }

        SysUserEntity sysUserEntity = baseDao.getUserInfobytoken(token);

        return ConvertUtils.sourceToTarget(sysUserEntity, SysUserDTO.class);
    }
}
